Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

88
Visualizações
React-pdf "Highlight text on the page" is not working

I am trying to implement React-pdf pdf highlighting feature:

import React, { useMemo, useState } from 'react';
// import { Document, Page } from 'react-pdf';
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';

import samplePDF from './test.pdf';

// https://gist.github.com/wojtekmaj/f265f55e89ccb4ce70fbd2f8c7b1d95d
function highlightPattern(text, pattern) {
  const splitText = text.split(pattern);

  if (splitText.length <= 1) {
    return text;
  }

  const matches = text.match(pattern);

  return splitText.reduce((arr, element, index) => (matches[index] ? [
    ...arr,
    element,
    <mark key={index}>
      {matches[index]}
    </mark>,
  ] : [...arr, element]), []);
}

export default function Test() {
  const [searchText, setSearchText] = useState('');

  // const textRenderer = useMemo((textItem) => {
  //   return highlightPattern(textItem.str, searchText);
  // }, [searchText]);

  function onChange(event) {
    setSearchText(event.target.value);
  }

  return (
    <>
      <Document
        file={samplePDF}
        // onLoadSuccess={onDocumentLoadSuccess}
      >
        <Page
          pageNumber={1}
          // customTextRenderer={textRenderer}
        />
      </Document>
      <div>
        <label htmlFor="search">Search:</label>
        <input type="search" id="search" value={searchText} onChange={onChange} />
      </div>
    </>
  );
}

Please note that I have commented the textRenderer function. If I uncomment it (still the Page component's prop is commented) application is crashed with

TypeError: Cannot read properties of undefined (reading 'str')

Reason could be textItem is null or undefined. But how can I fix this with useMemo?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Why are you not using useCallback as shown in the recipe

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda